package columnEditors;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import table.AbstractTable;



@SuppressWarnings("serial")
public class ButtonEditor extends DefaultCellEditor {
	  
	protected JButton button;

	private String    label;
	private boolean   isPushed;
	private AbstractTable abstractTable;
	private int row;
	 
	public ButtonEditor(AbstractTable abstractTable) {
		super(new JCheckBox());
		
		this.abstractTable = abstractTable;

		button = new JButton();
//		button.setEnabled(false);
		button.setOpaque(true);
	    button.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {
	    		fireEditingStopped();
	    	}
	    });
	  }
 
	
	public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
		
		if (isSelected) {
			button.setForeground(table.getSelectionForeground());
			button.setBackground(table.getSelectionBackground());
		} 
		else {
			button.setForeground(table.getForeground());
			button.setBackground(table.getBackground());
		}
		
		this.row = row;
		this.label = (value ==null) ? "" : value.toString();
		this.button.setText( label );
		this.isPushed = true;
		
		return this.button;
	}
 
	public Object getCellEditorValue() {
		if (isPushed)  {
			if (label.equals("Update"))
				updatePushed();
			else if (label.equals("Insert"))
				insertPushed();
    	}
		
		//Anti Insert i neste Selection hack
		String value = isPushed ? label : "";
		
		isPushed = false;
		
		return value ;
	}
  
	private void updatePushed() {
		abstractTable.updateRowInDatabase(row);
	}
	
	private void insertPushed() {
		abstractTable.insertLastRowToDatabase();
	}
   
	public boolean stopCellEditing() {
		isPushed = false;
		return super.stopCellEditing();
	}
 
	protected void fireEditingStopped() {
		super.fireEditingStopped();
	}
}
